import time
import os
import cv2
from mutagen.mp3 import MP3
import subprocess
from datetime import timedelta


def time_watcher():
    print('--- %s seconds ---' % (time.time() - start_time))


def get_items(extensions):
    items = []
    for root, subfolders, files in os.walk(os.getcwd()):
        for file in files:
            if file.split('.')[-1] in extensions:
                items.append(os.path.join(root, file))
    return items


def get_ffprobe_output(filename):
    filename = filename.replace(' ', '\ ')
    cmd = 'ffprobe -i {} -show_entries format=duration -v quiet -of csv="p=0"'.format(
        filename)
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT, universal_newlines=True)

    stdout, stderr = p.communicate()
    return int(float(stdout))


def get_duration_video(filename):
    # filename = filename.replace(' ', '\ ')
    video = cv2.VideoCapture(filename)

    fps = video.get(cv2.CAP_PROP_FPS)
    frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
    # duration = video.get(cv2.CAP_PROP_POS_MSEC)

    duration = frame_count/fps

    # return duration, frame_count
    return int(float(duration))


def get_duration_audio(filename):
    # filename = filename.replace(' ', '\ ')
    audio = MP3(filename)
    duration = audio.info.length

    return int(float(duration))


def seconds_to_str(s):
    return str(timedelta(seconds=s))


def main():
    extensions = ['mp4', 'avi']
    # extensions = ['mp3', 'wav']
    items = get_items(extensions)
    total_duration = 0

    for item in items:
        # duration = get_ffprobe_output(item)
        duration = get_duration_video(item)
        # duration = get_duration_audio(item)

        print(item.split('\\')[-1], 'Duration: ', seconds_to_str(duration))
        total_duration += duration

    print('Total_duration: ', seconds_to_str(total_duration))


if __name__ == '__main__':
    start_time = time.time()
    main()
    time_watcher()
